<?php 
// 1.连接数据库
try{
	$pdo = new PDO("mysql:host=localhost; dbname=jkxy;", "root", "");
}catch(PDOException $e){
	die("数据库连接失败".$e->getMessage());
}

// 2.通过action的值来选择对应的操作
switch($_GET['action']){
	case "add":
		// a.先取得提交过来的变量的值
		$name = $_POST['name'];
		$sex = $_POST['sex'];
		$age = $_POST['age'];
		$classid = $_POST['classid'];
		
		// b.再执行SQL语句把值插入到数据库中
		$sql = "insert into stu values(null, '{$name}', '{$sex}', '{$age}', '{$classid}')";
		$row = $pdo->exec($sql); // 执行SQL语句，返回的是影响的行数
		if($row > 0){
			echo "<script>alert('增加成功'); window.location='./index.php';</script>";
		}else{
			echo "<script>alert('增加失败'); window.history.back();</script>";
		}
		break;
		
	case "del":
		// a.先获取地址栏中传过来的要删除数据的id
		$id = $_GET['id'];
		
		// b.再执行SQL语句把这条数据删除
		$sql = "delete from stu where id={$id}"; // 写SQL语句
		$pdo->exec($sql); // 执行SQL语句，返回数据库中被影响的行数
		header("location:./index.php"); // 删除后跳转到index.php，等于刷新一下index.php
		break;
		
	case "edit":
		// a.获取表单的信息
		$id = $_POST['id'];
		$name = $_POST['name'];
		$sex = $_POST['sex'];
		$age = $_POST['age'];
		$classid = $_POST['classid'];
		
		// b.写SQL语句，执行SQL语句
		$sql = "update stu set name='{$name}', sex='{$sex}', age={$age}, classid={$classid} where id={$id}";
		$row = $pdo->exec($sql);
		if($row > 0){
			echo "<script>alert('修改成功'); window.location='index.php';</script>";
		}else{
			echo "<script>alert('修改失败'); window.history.back();</script>";
		}
		break;		
}


?>










